package codegen

import (
	"fmt"
	"gitee.com/hxchjm/goge/codegen/utils"
	"gitee.com/hxchjm/goge/codegen/utils/pathx"
	"github.com/siddontang/go/config"
	"path"
	"strings"
)

const (
	interval      = "internal/"
	configsDir    = "configs"
	cmdDir        = "cmd"
	apiDir        = "api"
	daoDir        = interval + "dao"
	appDir        = interval + "app"
	modelDir      = interval + "model"
	grpcDir       = interval + "server/grpc"
	httpDir       = interval + "server/http"
	serviceDir    = interval + "service"
	groupProperty = "group"
)

const mainTemplate = `package main

import (
	"flag"
	"os"
	"os/signal"
	"syscall"
	"time"
	
	{{.importPackages}}

	"go-main/library/conf"
	"go-main/library/log"
	"go-main/library/net/trace"	
)

func main() {
	flag.Parse()
	log.Init(nil) // debug flag: log.dir={path}
	defer log.Close()
	log.Info("{{.serviceName}} start")
	trace.Init(nil)
	defer trace.Close()
	if err := conf.Init(); err != nil {
		panic(err)
	}
	_, closeFunc, err := app.Init()
	if err != nil {
		panic(err)
	}
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
	for {
		s := <-c
		log.Info("get a signal %s", s.String())
		switch s {
		case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
			closeFunc()
			log.Info("{{.serviceName}} exit")
			time.Sleep(time.Second)
			return
		case syscall.SIGHUP:
		default:
			return
		}
	}
}`

func genMain(dir, rootPkg string, cfg *config.Config, filename string) error {
	//name := strings.ToLower(api.Service.Name)
	//filename, err := format.FileNamingFormat(cfg.NamingFormat, name)
	//if err != nil {
	//	return err
	//}

	/*	filename := name
		configName := filename
		if strings.HasSuffix(filename, "-api") {
			filename = strings.ReplaceAll(filename, "-api", "")
		}*/
	svcName := path.Base(rootPkg)
	return utils.GenFile(utils.FileGenConfig{
		Dir:          dir,
		Subdir:       cmdDir,
		Filename:     filename,
		TemplateName: "mainTemplate",
		//Category:        category,
		//TemplateFile:    mainTemplateFile,
		BuiltinTemplate: mainTemplate,
		Data: map[string]string{
			"importPackages": genMainImports(rootPkg),
			"serviceName":    svcName,
		},
	})
}

func genMainImports(parentPkg string) string {
	var imports []string
	//imports = append(imports, fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, apiDir)))
	imports = append(imports, fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, appDir)))
	//imports = append(imports, fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceURL))
	return strings.Join(imports, "\n\t")
}
